package com.example.qqlaobing.Umoney.view.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.qqlaobing.Umoney.R;
import com.example.qqlaobing.Umoney.been.PostBean;
import com.example.qqlaobing.Umoney.dialog.Dilog_TestingDate;
import com.example.qqlaobing.Umoney.net.NetRequestBusinessDefine;
import com.example.qqlaobing.Umoney.net.NetRequestRULBuilder;
import com.example.qqlaobing.Umoney.utils.ScrollTextViewView;
import com.example.qqlaobing.Umoney.view.activity.AgreeWebActivity;
import com.example.qqlaobing.Umoney.view.activity.CertificationCenterActivity;
import com.example.qqlaobing.Umoney.view.activity.LoanActivity1;
import com.example.qqlaobing.Umoney.view.activity.LoginActivity;
import com.example.qqlaobing.Umoney.view.activity.MainActivity;
import com.example.qqlaobing.Umoney.view.activity.MyWebView;
import com.example.qqlaobing.Umoney.view.activity.WebActivity;
import com.example.qqlaobing.Umoney.view.fragment.bean.AppLyLoan;
import com.example.qqlaobing.Umoney.view.fragment.bean.GlideImageLoader;
import com.example.qqlaobing.Umoney.view.fragment.bean.HomeBean;
import com.example.qqlaobing.Umoney.view.fragment.bean.HomeFq_listBean;
import com.example.qqlaobing.Umoney.view.fragment.home.Dilog_FeiYong;
import com.example.qqlaobing.Umoney.view.fragment.home.act.Act_LoanRecognition;
import com.example.qqlaobing.Umoney.view.myview.LoadingDialog;
import com.example.qqlaobing.Umoney.view.myview.PickerView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.gyf.barlibrary.ImmersionBar;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cc.ibooker.ztextviewlib.AutoVerticalScrollTextViewUtil;
import okhttp3.Call;

/**
 * 新的首页
 * Created by zhanglizhi on 2018/7/13.
 */

public class HomeFragment1 extends Fragment implements View.OnClickListener {
    @BindView(R.id.tv_auto)
    ScrollTextViewView tvAuto;
    @BindView(R.id.banner_auto)
    Banner bannerAuto;
    @BindView(R.id.tv_describle)
    TextView tv_describle;
    @BindView(R.id.tv_limitmoney)
    TextView tv_limitmoney;
    @BindView(R.id.bt_tvtv)
    TextView bt_tvtv;
    Unbinder unbinder;
    @BindView(R.id.myGif)
    ImageView myGif;
    @BindView(R.id.ll_button)
    LinearLayout ll_button;
    @BindView(R.id.loan_qs_desc)
    TextView loanQsDesc;
    @BindView(R.id.qishu)
    TextView qishu;
    @BindView(R.id.yue_fee_desc)
    TextView yueFeeDesc;
    @BindView(R.id.yue_fee)
    TextView yueFee;
    @BindView(R.id.fee_desc)
    TextView feeDesc;
    @BindView(R.id.view_desc)
    TextView viewDesc;
    @BindView(R.id.xieyiRadio)
    TextView xieyiRadio;
    @BindView(R.id.userXieyi)
    TextView userXieyi;
    @BindView(R.id.tv_card_no)
    TextView tvCardNo;
    @BindView(R.id.ll_card)
    LinearLayout llCard;
    @BindView(R.id.tv_certificationcenter)
    ImageView tvCertificationcenter;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.pv_money)
    PickerView pvMoney;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.iv_clock)
    ImageView ivClock;
    @BindView(R.id.pv_time)
    PickerView pvTime;
    @BindView(R.id.ll_loanmoney)
    LinearLayout llLoanmoney;
    @BindView(R.id.lijijieqian)
    LinearLayout lijijieqian;
    @BindView(R.id.my_shouwtubiao)
    LinearLayout myShouwtubiao;
    @BindView(R.id.top_desc)
    TextView top_desc;
    @BindView(R.id.waring)
    TextView waring;
    private View rootView;
    private AutoVerticalScrollTextViewUtil autoVerticalScrollTextViewUtil;
    private List list = new ArrayList();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_home1, container, false);
        unbinder = ButterKnife.bind(this, rootView);
        status = true;
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        unbinder = ButterKnife.bind(this, rootView);
        ImmersionBar.with(this).statusBarDarkFont(false).init();
        initView();
    }

    LoadingDialog dialog;
    Dilog_TestingDate testingDate;
    Dilog_FeiYong dilog_feiYong;

    private void initView() {
        dialog = new LoadingDialog(getContext(), "玩命加载中...");
        bt_tvtv.setOnClickListener(this);
        testingDate = new Dilog_TestingDate(getContext());
        xieyiRadio.setSelected(true);
//        dialog.show();
        postData();
        start();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_tvtv:
                if (homeBean == null) {
                    return;
                }
                if (homeBean.getData() == null) {
                    return;
                }
                if (xieyiRadio.isSelected() == false) {
                    Toast.makeText(getContext(), "请选中借款协议！", Toast.LENGTH_LONG).show();
                    return;
                }
                if (homeBean.getData().getData().getAuthstatus() == 1) {
                    if (homeBean.getData().getData().getLoan() == null || homeBean.getData().getData().getLoan().equals("null")) {//走获取额度
                        postapplyLoan(); //获取额度  postapplyLoan(); //获取额度
                    } else {
                        switch (homeBean.getData().getData().getLoan().getStatus()) {
                            case "0"://审核中
                                Toast.makeText(getContext(), homeBean.getData().getData().getBtn_desc(), Toast.LENGTH_LONG).show();
                                break;
                            case "1":
                                if (homeBean.getData().getData().getLoan().getShenhestatus().equals("1") &&
                                        homeBean.getData().getData().getLoan().getStatus1().equals("0")) {//下一步
                                    postselectProducts();
//                                    Intent intent1 = new Intent(getContext(), LoanActivity1.class);//以前的确认贷款页面
//                                    startActivity(intent1);
                                } else if ((homeBean.getData().getData().getLoan().getShenhestatus().equals("1") &&
                                        homeBean.getData().getData().getLoan().getStatus1().equals("1"))) {//放款中
                                    Toast.makeText(getContext(), homeBean.getData().getData().getBtn_desc(), Toast.LENGTH_LONG).show();
                                } else {//被拒绝===下载页面
                                    String h5_url = homeBean.getData().getData().getLoan().getH5_url();
                                    Intent intent = new Intent();
                                    intent.setClass(getContext(), WebActivity.class);
                                    intent.putExtra("title","no");
                                    intent.putExtra("url", h5_url);
                                    startActivityForResult(intent,10);
                                }
                                break;
                            case "2"://立即还款 h5
//                                testingDate.show();
//                                testingDate.setOnBackTime(new Dilog_TestingDate.OnBackCenter() {
//                                    @Override
//                                    public void onHuanKuan() {
                                String Pay_url = homeBean.getData().getData().getLoan().getPay_url();
                                Intent intent = new Intent();
                                intent.setClass(getContext(), MyWebView.class);
                                intent.putExtra("url", NetRequestBusinessDefine.K_HOST_NAME + Pay_url);
                                startActivity(intent);
//                                    }
//
//                                    @Override
//                                    public void onYanqi() {
//                                        String Pay_url = homeBean.getData().getData().getLoan().getDelay_pay_url();
//                                        Intent intent = new Intent();
//                                        intent.setClass(getContext(), MyWebView.class);
//                                        intent.putExtra("url", NetRequestBusinessDefine.K_HOST_NAME + Pay_url);
//                                        startActivity(intent);
//                                    }
//                                });

                                break;
                            case "3":

                                break;
                            case "4":

                                break;
                            default:

                                break;
                        }

                    }
                } else {//认证界面
                    Toast.makeText(getActivity(), "请先完善认证资料", Toast.LENGTH_SHORT).show();
//                    MainActivity mainActivity5 = (MainActivity) getActivity();
//                    startActivity(new Intent(mainActivity5, RenZhengActivity.class));
//                    mainActivity5.finish();
                    startActivity(new Intent(getActivity(), CertificationCenterActivity.class));
                }
                break;
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==10&&resultCode==10){
            postData();
        }

    }

    private boolean status = false;

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    HomeBean homeBean;
    boolean myGifStatus = false;

    /**
     * 获取首页数据
     */
    public void postData() {
        OkHttpUtils
                .post()
                .url(NetRequestRULBuilder.buildRequestUrl(NetRequestBusinessDefine.K_HOME))
                .addHeader("token", NetRequestBusinessDefine.K_TOKEN)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        dialog.close();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        dialog.close();
                        Gson gson = new Gson();
                        homeBean = gson.fromJson(response, HomeBean.class);
                        if (homeBean.getStatus() == 1) {
                            LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
                            if(homeBean.getData().getData().getLoan()==null){
                                bt_tvtv.setSelected(false);
                                myGif.setVisibility(View.GONE);
                                myGifStatus = false;
                                layoutParam.setMargins(0, 0, 0, 0);
                                tv_limitmoney.setPadding(0, 0, 0, 0);
                                tv_limitmoney.setTextSize(40);
                                unbinder = ButterKnife.bind(this, rootView);
                                tv_limitmoney.setText("￥" + homeBean.getData().getData().getAmount_limit());//设置额度
                            }else {
                                switch (homeBean.getData().getData().getLoan().getStatus()) {
                                    case "0"://审核中
                                        bt_tvtv.setSelected(true);
                                        myGif.setVisibility(View.VISIBLE);
                                        tv_limitmoney.setPadding(0, 40, 0, 0);
                                        tv_limitmoney.setText("额度审批中...");
                                        tv_limitmoney.setTextSize(20);
                                        layoutParam.setMargins(0, 0, 0, 20);
                                        break;
                                    default:
//                                            if (homeBean.getData().getData().getAmount_limit() != null) {
                                        bt_tvtv.setSelected(false);
                                        myGif.setVisibility(View.GONE);
                                        myGifStatus = false;
                                        layoutParam.setMargins(0, 0, 0, 0);
                                        tv_limitmoney.setPadding(0, 0, 0, 0);
                                        tv_limitmoney.setTextSize(40);
                                        unbinder = ButterKnife.bind(this, rootView);
                                        tv_limitmoney.setText("￥" + homeBean.getData().getData().getAmount_limit());//设置额度
//                                            }
                                        break;
                                }
                            }

                            if (homeBean.getData().getData().getLoan()!=null&&homeBean.getData().getData().getLoan().getStatus().equals("1") && homeBean.getData().getData().getBtn_desc().equals("立即提现")) {
                                myShouwtubiao.setVisibility(View.GONE);
                                bannerAuto.setVisibility(View.GONE);
                                lijijieqian.setVisibility(View.VISIBLE);
                                loanQsDesc.setText(homeBean.getData().getData().getLoan_qs_desc());
                                qishu.setText(homeBean.getData().getData().getLoan().getQs() + "期");
                                yueFeeDesc.setText(homeBean.getData().getData().getYue_fee_desc());
                                yueFee.setText(homeBean.getData().getData().getYue_fee());
                            } else {
                                myShouwtubiao.setVisibility(View.VISIBLE);
                                bannerAuto.setVisibility(View.VISIBLE);
                                lijijieqian.setVisibility(View.GONE);
                            }
                            ll_button.setGravity(Gravity.CENTER);
                            ll_button.setLayoutParams(layoutParam);
                            bt_tvtv.setText(homeBean.getData().getData().getBtn_desc());
                            tv_describle.setText(homeBean.getData().getData().getLoan_desc());
                            for (int i = 0; i < homeBean.getData().getData().getLatest_loads().size(); i++) {
                                list.add(homeBean.getData().getData().getLatest_loads().get(i).getTelephone() + "成功借款" + homeBean.getData().getData().getLatest_loads().get(i).getAmount() + "元");
                            }
                            autoVerticalScrollTextViewUtil = new AutoVerticalScrollTextViewUtil(tvAuto, (ArrayList<CharSequence>) list);
                            // 设置滚动的时间间隔
                            autoVerticalScrollTextViewUtil.setDuration(5000);
                            autoVerticalScrollTextViewUtil.stop();
                            // 开启滚动
                            autoVerticalScrollTextViewUtil.start();
                            if (homeBean.getData().getData().getLoan() != null) {
                                NetRequestBusinessDefine.oderno = homeBean.getData().getData().getLoan().getId();
                                NetRequestBusinessDefine.oderid = homeBean.getData().getData().getLoan().getOrderno();
                            }
                            final List<String> images = new ArrayList<>();
                            final List<String> urls = new ArrayList<>();
                            for (int i = 0; i < homeBean.getData().getData().getAds().size(); i++) {
                                images.add(homeBean.getData().getData().getAds().get(i).getImage());
                                urls.add(homeBean.getData().getData().getAds().get(i).getUrl());
                            }
                            top_desc.setText(homeBean.getData().getData().getTop_desc());
                            waring.setText("*"+homeBean.getData().getData().getBottom_hint()+"*");
                            viewDesc.setText(homeBean.getData().getData().getView_desc());
                            bannerAuto.setImageLoader(new GlideImageLoader());
                            bannerAuto.setImages(images);
                            bannerAuto.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
                            bannerAuto.isAutoPlay(true);
                            bannerAuto.setDelayTime(5000);
                            bannerAuto.start();
                            bannerAuto.setOnBannerListener(position -> {
                                if (urls.get(position).equals("") || urls.get(position) == null) {
                                    return;
                                }
                                Intent intent = new Intent(getActivity(), WebActivity.class);
                                intent.putExtra("url", urls.get(position));
                                startActivity(intent);
                            });
//                            JSONObject jsonObject = null;
//                            try {
//                                jsonObject = new JSONObject(response);
//                                JSONObject jsonObject1 = new JSONObject(jsonObject.getString("data"));
//                                JSONObject jsonObject2 = new JSONObject(jsonObject1.getString("data"));
//                                String loan = jsonObject2.getString("loan");
//                                jsonObject = new JSONObject(loan);
//                                String fqstr = jsonObject.getString("fq_list");
//                                fqstr=fqstr.replace(",\"1\"","");
//                                Log.e("aa","-------fq_list=="+fq_list.length());
//                                JSONArray fq_list = jsonObject.getJSONArray(fqstr);
//                                List<HomeFq_listBean> beans = new ArrayList<>();
////                                for (int i = 0; i < fq_list.length(); i++) {
////                                    String Json = fq_list.getString(i);
////                                    if (Json.equals("1")) {
////                                    } else {
////                                        HomeFq_listBean bean = gson.fromJson(Json, HomeFq_listBean.class);
////                                        beans.add(bean);
////                                    }
////                                }
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
                        } else if (homeBean.getStatus() == 401) {
                            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("umoney", Activity.MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                            editor.putString("token", "");
                            editor.commit();//提交修改
                            NetRequestBusinessDefine.loan = true;
                            startActivity(new Intent(getContext(), LoginActivity.class));
                            getActivity().finish();
                        } else {
                            if (status) {
                                Toast.makeText(getContext(), "网络异常！", Toast.LENGTH_LONG).show();
                                status = false;
                            }
                        }
                    }
                });
    }

    /**
     * 获取额度
     */
    public void postapplyLoan() {
        OkHttpUtils
                .post()
                .url(NetRequestRULBuilder.buildRequestUrl(NetRequestBusinessDefine.K_GET_MONEY))
                .addHeader("token", NetRequestBusinessDefine.K_TOKEN)
                .addParams("days", "7")
                .addParams("amount", "10000")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        dialog.close();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        dialog.close();
                        Gson gson = new Gson();
                        AppLyLoan appLyLoan = gson.fromJson(response, AppLyLoan.class);
                        if (appLyLoan.getStatus() == 1) {
                            postData();//刷新首页显示状态
                            Toast.makeText(getContext(), appLyLoan.getData().getData().getInfo(), Toast.LENGTH_LONG).show();
                        } else if (homeBean.getStatus() == 401) {
                            if (LoginActivity.LoginActivityStatus == false) {
                                startActivity(new Intent(getContext(), LoginActivity.class));
                                getActivity().finish();
                            }
                        } else {
                            if (status) {
                                Toast.makeText(getContext(), "网络异常！", Toast.LENGTH_LONG).show();
                                status = false;
                            }
                        }
                    }
                });
    }

    // 计时器
    private Timer timer;

    /**
     * @param
     * @return void
     * @throws
     * @Description: 开始计时
     */
    public void start() {
        if (timer == null) {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    postData();
                    i++;
                }
            }, 0, 7000);
        }
    }

    int i = 0;

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

    @OnClick({R.id.view_desc, R.id.userXieyi, R.id.xieyiRadio})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.view_desc://费用详情
                if (homeBean == null) {
                    return;
                }
                dilog_feiYong = new Dilog_FeiYong(getContext(), homeBean, () -> {

                });
                dilog_feiYong.show();
                break;
            case R.id.userXieyi://协议
                Intent intent1 = new Intent(getContext(), AgreeWebActivity.class);
                startActivity(intent1);
                break;
            case R.id.xieyiRadio://协议是否选中阅读
                if (xieyiRadio.isSelected()) {
                    xieyiRadio.setSelected(false);
                } else {
                    xieyiRadio.setSelected(true);
                }
                break;
        }
    }



    /**
     * 立即提现提交数据
     */
    public void postselectProducts() {
        dialog = new LoadingDialog(getContext(), "上传中...");
        dialog.show();
        OkHttpUtils
                .post()
                .url(NetRequestRULBuilder.buildRequestUrl(NetRequestBusinessDefine.K_POST_APPLY))
                .addHeader("token", NetRequestBusinessDefine.K_TOKEN)
                .addParams("orderno", NetRequestBusinessDefine.oderid)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        dialog.close();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        dialog.close();
                        PostBean appLyLoan = gson.fromJson(response, PostBean.class);
                        if (appLyLoan.getStatus() == 1) {
                            postData();
                            Toast.makeText(getContext(), appLyLoan.getMsg(), Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(getContext(), appLyLoan.getMsg(), Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }

}
